<?php

namespace app\admin\controller;
use app\admin\model\SchoolModel;
use app\admin\model\MemberModel;
use app\admin\model\UserType;
use think\Db;


class School extends Base
{

    public function index(){

        $uid= session('uid');
        $instit_id = session('instit_id');


        $key = input('key');
        $map = [];
        $map2 =[];
        if($key&&$key!==""){
            $map['shuren_student.studentName'] = ['like',"%" . $key . "%"];
            $map['shuren_student.studentCode'] = ['like',"%" . $key . "%"];
//            $map['shuren_student.studentCode'] = ['eq', $key];

            $map2['studentName'] = ['like',"%" . $key . "%"];
            $map2['studentCode'] = ['eq', $key];
        }

        $Nowpage = input('get.page') ? input('get.page'):1;
        $limits = 10;// 获取总条数

        if($uid>1){
            $map['shuren_instit.id'] = $instit_id;
            $map2['instit_id'] = $instit_id;
        }
        $count = Db::name('student')->whereOr($map2)->count();//计算总页面
        $allpage = intval(ceil($count / $limits));
        $article = new SchoolModel();
        $lists = $article->getSchoolByWhere($map, $Nowpage, $limits);
        $this->assign('Nowpage', $Nowpage); //当前页
        $this->assign('allpage', $allpage); //总页数
        $this->assign('count', $count);
        $this->assign('val', $key);
        $this->assign('list', $lists);
        if(input('get.page')){
            return json($lists);
        }
        return $this->fetch();
    }

    public function school_state(){
        $id = input('param.id');
        $status = Db::name('student')->where('id',$id)->value('status');//判断当前状态情况
        if($status==1)
        {
            $flag = Db::name('student')->where('id',$id)->setField(['status'=>0]);
            return json(['code' => 1, 'data' => $flag['data'], 'msg' => '已禁用']);
        }
        else
        {
            $flag = Db::name('student')->where('id',$id)->setField(['status'=>1]);
            return json(['code' => 0, 'data' => $flag['data'], 'msg' => '已开启']);
        }
    }

    /**
     * [add_cate 添加学籍]
     * @return [type] [description]
     * @author [沈晶晶] [334554156@qq.com]
     */
    public function school_add()
    {
        $instit_id = session('instit_id');
        if(request()->isAjax()){
            $param = input('post.');
            $edu = new SchoolModel();
            $param['instit_id'] = $instit_id;

            $info = array(
                'instit_id' => session('instit_id'),
                'studentCode' => $param['studentCode'],
            );


            $count11 = Db::name('member')->where('account',$param['mobile'])->count();//计算总页面
            if($count11>0){
                return  json(['code' => -2, 'data' => '', 'msg' =>'该手机号码已占用']);
            }

            $count1 = Db::name('student')->where($info)->count();//计算总页面
            if($count1==0){
                $flag = $edu->insertSchool($param);
                if ($flag['code'] == 1) {
                    $membermodel = new MemberModel();
                    $member = array(
                        'account' => $param['mobile'],
                        'realname' => $param['studentName'],
                        'nickname' => $param['studentName'],
                        'status'=>1,
                        'group_id'=>1,
                        'create_time'=>time(),
                    );
                    $count = Db::name('member')->where($member)->count();//计算总页面
                    if ($count == 0) {
                        $password = substr($param['mobile'], -6);
                        //$member['password'] = md5(md5($password) . config('auth_key'));
                        $membermodel->insertMember($member);
                    }
                }
                return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
            }else{
               return  json(['code' => -2, 'data' => '', 'msg' =>'该学生编号已占用']);
            }
        }
        return $this->fetch();
    }


    /**
     * [edit_cate 编辑学籍]
     * @return [type] [description]
     * @author [沈晶晶] [334554156@qq.com]
     */
    public function school_edit()
    {
        $cate = new SchoolModel();
        if(request()->isAjax()){
            $param = input('post.');

            $flag = $cate->updateSchool($param);
            return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
        }

        $id = input('param.id');

        $this->assign('school',$cate->getOneSchool($id));
        return $this->fetch();
    }


    public function import()
    {
        $edu = new SchoolModel();
        if(request()->isAjax()){

                        $param = input('post.');
                        require_once getcwd() . '/phpexcel/Classes/PHPExcel.php';     //修改为自己的目录
                        require_once getcwd() . '/phpexcel/Classes/PHPExcel/IOFactory.php';     //修改为自己的目录
                        require_once getcwd() . '/phpexcel/Classes/PHPExcel/Reader/Excel5.php';     // 用于其他低版本xls
                        require_once getcwd() . '/phpexcel/Classes/PHPExcel/Reader/Excel2007.php'; // 用

                       $filePath = getcwd() . '/uploads/file/'.$param['ufile'];
                        $PHPExcel = new \PHPExcel();
                        /**默认用excel2007读取excel，若格式不对，则用之前的版本进行读取*/
                        $PHPReader = new \PHPExcel_Reader_Excel2007();
                        if (!$PHPReader->canRead($filePath)) {
                            $PHPReader = new \PHPExcel_Reader_Excel5();
                            if (!$PHPReader->canRead($filePath)) {
                                echo '导入文件有误';
                                return;
                            }
                        }
                        $PHPExcel = $PHPReader->load($filePath);
                        $currentSheet = $PHPExcel->getSheet(0);  //读取excel文件中的第一个工作表
                        $allColumn = $currentSheet->getHighestColumn(); //取得最大的列号
                        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
                        $erp_orders_id = array();  //声明数组

                        /**从第二行开始输出，因为excel表中第一行为列名*/
                        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                            /**从第A列开始输出*/
                            for ($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn++) {
                                $val = $currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65, $currentRow)->getValue();
                                /**ord()将字符转为十进制数*/
                                $excel_data[$currentRow][] = $val;
                            }
                        }

                        $strs1 = '';
                        foreach($excel_data as $key=>$val) {

                             $userz = Db::name('member')->where('account',$val[13])->find();

                                if($userz){
                                    $strs1 = $strs1. "第".$key."行：手机号码已占用！<br>";
                                }else{
                                    $info = array(
                                        'instit_id' => session('instit_id'),
                                        'studentCode' => $val[1],
                                    );
                                    $count1 = Db::name('student')->where($info)->count();//计算总页面
                                    if($count1>0){
                                        $strs1 = $strs1. "第".$key."行：该学生编码已存在！<br>";
                                    }else{
                                        if ($val[2] == '男') {
                                            $sex = 0;
                                        } else {
                                            $sex = 1;
                                        }
                                        $studut = array(
                                            'instit_id' => session('instit_id'),
                                            'studentCode' => $val[1],
                                            'studentName' => $val[0],
                                            'sex' => $sex,
                                            'birthday' => $val[3],
                                            'birthplace' => $val[4],
                                            'recruitment' => $val[5],
                                            'nation' => $val[6],
                                            'country' => $val[7],
                                            'certificatetype' => 0,
                                            'peopleID' => $val[8],
                                            'political' => $val[10],
                                            'healthstatus' => $val[11],
                                            'address' => $val[12],
                                            'mobile' => $val[13],
                                            'postcode' => $val[14],
                                            'jionyear' => $val[15],
                                        );

                                        $flag = $edu->importSchool($studut);
                                        if ($flag['code'] == 1) {
                                            $membermodel = new MemberModel();
                                            $member = array(
                                                'account' => $studut['mobile'],
                                                'nickname' => $studut['studentName'],
                                                'realname' => $studut['studentName'],
                                                'status'=>1,
                                                'group_id'=>1,
                                                'create_time'=>time(),
                                                'instit_id'=>session('instit_id'),
                                            );
                                            $count = Db::name('member')->where($member)->count();//计算总页面
                                            if ($count == 0) {
                                                $password = substr($studut['mobile'], -6);
                                                $member['password'] =  md5(md5($password) . config('auth_key'));;
                                                $membermodel->insertMember($member);
                                            }
                                        }


                                    }
                                }
                        }

                        if($strs1==''){
                            return json(['code'=>1,'msg'=>'导入成功']);
                        }else{
                            return json(['code'=>-1,'msg'=>$strs1."其他数据导入成功！"]);
                        }

                }

        return $this->fetch();
    }

    public function teach(){
        $uid= session('uid');
        $instit_id = session('instit_id');
        //print_R($admin);
        $key = input('key');
        $map = [];
        if($key&&$key!==""){
            $map['shuren_teach.name'] = ['like',"%" . $key . "%"];
           // $map['think_student.studentCode'] = ['eq', $key];
        }
        $Nowpage = input('get.page') ? input('get.page'):1;
        $limits = 10;// 获取总条数
        if($uid>1){
            $map['shuren_teach.instit_id'] = $instit_id;
        }
        $count = Db::name('teach')->where($map)->count();//计算总页面
        $allpage = intval(ceil($count / $limits));
        $article = new SchoolModel();
        $lists = $article->getTeachByWhere($map, $Nowpage, $limits);
        $this->assign('Nowpage', $Nowpage); //当前页
        $this->assign('allpage', $allpage); //总页数
        $this->assign('count', $count);
        $this->assign('val', $key);
        $this->assign('list', $lists);
        if(input('get.page')){
            return json($lists);
        }
        return $this->fetch();
    }

    public function teach_state(){
        $id = input('param.id');
        $status = Db::name('teach')->where('id',$id)->value('status');//判断当前状态情况
        if($status==1)
        {
            $flag = Db::name('teach')->where('id',$id)->setField(['status'=>0]);
            return json(['code' => 1, 'data' => $flag['data'], 'msg' => '已禁用']);
        }
        else
        {
            $flag = Db::name('teach')->where('id',$id)->setField(['status'=>1]);
            return json(['code' => 0, 'data' => $flag['data'], 'msg' => '已开启']);
        }
    }


    /**
     * [add_cate 添加教师]
     * @return [type] [description]
     * @author [沈晶晶] [334554156@qq.com]
     */
    public function teach_add()
    {
        $instit_id = session('instit_id');
        if(request()->isAjax()){
            $param = input('post.');
            $edu = new SchoolModel();
            $param['instit_id'] = $instit_id;

            $count11 = Db::name('member')->where('account',$param['mobile'])->count();//计算总页面
            if($count11>0){
                return  json(['code' => -2, 'data' => '', 'msg' =>'该手机号码已占用']);
            }


            $info = array(
                'instit_id' => session('instit_id'),
                'mobile' => $param['mobile'],
            );
            $count1 = Db::name('teach')->where($info)->count();//计算总页面

            $info1 = array(
                'instit_id' => session('instit_id'),
                'title' => '老师',
            );
            $count2 = Db::name('auth_group')->where($info1)->count();//计算总页面

            if($count2>0){

                if($count1==0){

                    $flag = $edu->insertTeach($param);

                    if ($flag['code'] == 1) {
                        $membermodel = new MemberModel();
                        $member = array(
                            'account' => $param['mobile'],
                            'nickname' => $param['name'],
                            'realname' => $param['name'],
                            'status'=>1,
                            'group_id'=>9,
                            'create_time'=>time(),
                        );
                        $count = Db::name('member')->where($member)->count();//计算总页面

                        if ($count == 0) {
                            $password = substr($param['mobile'], -6);
                            $member['password'] = '';
                           // $member['password'] = md5(md5($password) . config('auth_key'));
                            $membermodel->insertMember($member);
                        }


                        $psd1 =substr($param['mobile'], -6);

                        $teach_auth = Db::name('auth_group')->where($info1)->find();//计算总页面

                        $admin_user = array(
                            'username'=>$param['mobile'],
                            'password'=>md5(md5($psd1) . config('auth_key')),
                            'groupid'=>$teach_auth['id'],
                            'instit_id'=>session('instit_id'),
                            'real_name'=>$param['name'],
                            'status'=>1,
                        );

                       $new_id =  Db::name('admin')->insertGetId($admin_user);

                        $accdata = array(
                            'uid'=> $new_id,
                            'group_id'=> $teach_auth['id'],
                        );
                        $group_access = Db::name('auth_group_access')->insert($accdata);
                    }
                    return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
                }else{
                    return  json(['code' => -2, 'data' => '', 'msg' =>'该手机号码已占用']);
                }


            }else{
                return  json(['code' => -2, 'data' => '', 'msg' =>'请在 系统管理-角色管理 下新建 老师 的权限组后在进行添加！']);
            }
        }


        $instit  = Db::name('instit')->where('id='.$instit_id)->find();
        if($instit['school']>0){
            $nianji  = Db::name('nianji')->where('schoollevel='.$instit['school'])->order('id asc')->select();
            $this->assign('nianji', $nianji);
        }

        $map = array(
            'instit_id'=>$instit_id,
            'status'=>1
        );
        $course  = Db::name('course ')->where($map)->order('id asc')->select();
        $role = new UserType();
        $this->assign('role',$role->getRole());
        $this->assign('course', $course);
        return $this->fetch();
    }


    public function teach_edit()
    {
        $instit_id = session('instit_id');
        $cate = new SchoolModel();
        if(request()->isAjax()){
            $param = input('post.');
            $flag = $cate->updateTeach($param);
            return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
        }

        $id = input('param.id');

        $instit  = Db::name('instit')->where('id='.$instit_id)->find();
        if($instit['school']>0){
            $nianji  = Db::name('nianji')->where('schoollevel='.$instit['school'])->order('id asc')->select();
            $this->assign('nianji', $nianji);
        }

        $map = array(
            'instit_id'=>$instit_id,
            'status'=>1
        );
        $course  = Db::name('course ')->where($map)->order('id asc')->select();
        $role = new UserType();
        $this->assign('role',$role->getRole());
        $this->assign('course', $course);

        $this->assign('teach',$cate->getOneTeach($id));
        return $this->fetch();
    }



    public function teach_import()
    {
        $edu = new SchoolModel();
        if(request()->isAjax()){

            $param = input('post.');
            require_once getcwd() . '/phpexcel/Classes/PHPExcel.php';     //修改为自己的目录
            require_once getcwd() . '/phpexcel/Classes/PHPExcel/IOFactory.php';     //修改为自己的目录
            require_once getcwd() . '/phpexcel/Classes/PHPExcel/Reader/Excel5.php';     // 用于其他低版本xls
            require_once getcwd() . '/phpexcel/Classes/PHPExcel/Reader/Excel2007.php'; // 用

            $filePath = getcwd() . '/uploads/file/'.$param['ufile'];
            $PHPExcel = new \PHPExcel();
            /**默认用excel2007读取excel，若格式不对，则用之前的版本进行读取*/
            $PHPReader = new \PHPExcel_Reader_Excel2007();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_Excel5();
                if (!$PHPReader->canRead($filePath)) {
                    echo '导入文件有误';
                    return;
                }
            }
            $PHPExcel = $PHPReader->load($filePath);
            $currentSheet = $PHPExcel->getSheet(0);  //读取excel文件中的第一个工作表
            $allColumn = $currentSheet->getHighestColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $erp_orders_id = array();  //声明数组

            /**从第二行开始输出，因为excel表中第一行为列名*/
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                /**从第A列开始输出*/
                for ($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65, $currentRow)->getValue();
                    /**ord()将字符转为十进制数*/
                    $excel_data[$currentRow][] = $val;
                }
            }


            $instit_info = Db::name('instit')->where('id',session('instit_id'))->find();
            $nianji = Db::name('nianji')->field('id,nianji')->where('schoollevel',$instit_info['school'])->select();
            $kecheng =Db::name('course')->field('id,name')->where('instit_id',session('instit_id'))->select();

            foreach($excel_data as $key=>$val) {
                $userz = Db::name('member')->where('account',$val[3])->find();
                $strs1 = '';
                if($userz){
                    $strs1 = $strs1. "第".$key."行：手机号码已占用！<br>";
                }else{

                                $info = array(
                                    'instit_id' => session('instit_id'),
                                    'mobile' => $val[3],
                                );
                                $count1 = Db::name('teach')->where($info)->count();//计算总页面

                                $info1 = array(
                                    'instit_id' => session('instit_id'),
                                    'title' => '老师',
                                );
                                $count2 = Db::name('auth_group')->where($info1)->count();//计算总页面
                //
                                if ($count2 > 0) {
                //
                                    if ($count1 == 0) {
                                        $param1 = array();
                                        $param1['instit_id'] = session('instit_id');
                                        $param1['name'] = $val[0];
                                        // $param1['createtime'] = time() ;
                                        $param1['teach_sn'] = $val[1];
                                        $param1['mobile'] = $val[3];
                                        if ($val[6] == '是') {
                                            $param1['is_leader'] = 1;
                                        } else {
                                            $param1['is_leader'] = 0;
                                        }
                                        $param1['status'] = 1;
                                        if ($val[2] == '男') {
                                            $param1['sex'] = 0;
                                        } elseif ($val[2] == '女') {
                                            $param1['sex'] = 1;
                                        } else {
                                            $param1['sex'] = '';
                                        }

                                        foreach ($nianji as $key => $vv) {
                                            if ($vv['nianji'] == $val[4]) {
                                                $param1['nianji'] = $vv['id'];
                                            }
                                        }

                                        foreach ($kecheng as $key => $vq) {
                                            if ($vq['name'] == $val[5]) {
                                                $param1['course'] = $vq['id'];
                                            }
                                        }

                                        $flag = $edu->insertTeach($param1);

                                        if ($flag['code'] == 1) {

                                            $membermodel = new MemberModel();
                                            $member = array(
                                                'account' => $param1['mobile'],
                                                'realname' => $param1['name'],
                                                'nickname' => $param1['name'],
                                                'status' => 1,
                                                'group_id' => 9,
                                                'create_time' => time(),
                                            );

                                            $count = Db::name('member')->where($member)->count();//计算总页面
                                            if ($count == 0) {
                                                $password = substr($param1['mobile'], -6);
                                                $member['password'] = md5(md5($password) . config('auth_key'));;
                                                // $member['password'] = md5(md5($password) . config('auth_key'));
                                                $membermodel->insertMember($member);
                                            }


                                            $psd1 = substr($param1['mobile'], -6);

                                            $teach_auth = Db::name('auth_group')->where($info1)->find();//计算总页面

                                            $admin_user = array(
                                                'username' => $param1['mobile'],
                                                'password' => md5(md5($psd1) . config('auth_key')),
                                                'groupid' => $teach_auth['id'],
                                                'instit_id' => session('instit_id'),
                                                'real_name' => $param1['name'],
                                                'status' => 1,
                                            );

                                            $new_id = Db::name('admin')->insertGetId($admin_user);

                                            $accdata = array(
                                                'uid' => $new_id,
                                                'group_id' => $teach_auth['id'],
                                            );
                                            $group_access = Db::name('auth_group_access')->insert($accdata);
                                        }

                                    } else {
                                        $strs1 = $strs1. "第".$key."行：学校已存在此号码的老师，请勿重复添加！<br>";
                                    }


                                } else {
                                    return json(['code' => -2, 'data' => '', 'msg' => '请在 系统管理-角色管理 下新建 老师 的权限组后在进行添加！']);
                                }


                            }
            }

            if($strs1==''){
                return json(['code'=>1,'msg'=>'导入成功']);
            }else{
                return json(['code'=>-1,'msg'=>$strs1."其他数据导入成功！"]);
            }
        }

        return $this->fetch();
    }



}